package com.lxw.manage_cms.service;

import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.CmsSite;
import com.lxw.framework.domain.cms.request.QueryPageRequest;

import com.lxw.manage_cms.dao.CmsPageDao;
import com.lxw.manage_cms.dao.CmsSiteDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CmsPageServiceImpl implements  ICmsPageService {
    @Autowired
    CmsPageDao cmsPageDao;


    @Override
    public Page<CmsPage> findList(Integer page, Integer pageSize, QueryPageRequest queryPageRequest) {

        CmsPage cmsPage = new CmsPage();
        if(StringUtils.isNotEmpty(queryPageRequest.getTemplateId())){
            cmsPage.setTemplateId(queryPageRequest.getTemplateId());
        }
        if(StringUtils.isNotEmpty(queryPageRequest.getSiteId())){
            cmsPage.setSiteId(queryPageRequest.getSiteId());
        }
        if(StringUtils.isNotEmpty(queryPageRequest.getPageAliase())){
            cmsPage.setPageAliase(queryPageRequest.getPageAliase());
        }

        //页面别名 模糊匹配
        ExampleMatcher.GenericPropertyMatcher contains = ExampleMatcher.GenericPropertyMatchers.contains();
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("pageAliase",contains);
        Example<CmsPage> example = Example.of(cmsPage,exampleMatcher);

        page -= 1;  //页码从0开始
        PageRequest of = PageRequest.of(page,pageSize);
        Page<CmsPage> all = cmsPageDao.findAll(example,of);

        return all;
    }

    @Override
    public void save(CmsPage cmsPage) {
        //1.在cms_page集中上创建页面名称、站点Id、页面webpath为唯一索引
        CmsPage cmsPage2 = new CmsPage();
        cmsPage2.setPageName(cmsPage.getPageName());
        cmsPage2.setSiteId(cmsPage.getSiteId());
        cmsPage2.setPageWebPath(cmsPage.getPageWebPath());

        Example<CmsPage> example = Example.of(cmsPage);
        long count = cmsPageDao.count(example);
        if (count>0){
            throw new  RuntimeException("创建页面名称、站点Id、页面webpath必须唯一");
        }

        //2.保存
        cmsPageDao.save(cmsPage);
    }

}
